package com.qijian.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Constants;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qijian.common.core.domain.entity.SysUser;
import com.qijian.common.exception.ServiceException;
import com.qijian.common.utils.ObjectUtils;
import com.qijian.common.utils.StringUtils;
import com.qijian.common.utils.mybatis.WhereEntityTool;
import com.qijian.common.utils.uuid.IdUtils;
import com.qijian.system.domain.Remind;
import com.qijian.system.domain.RemindUsers;
import com.qijian.system.domain.vo.RemindQuery;
import com.qijian.system.domain.vo.RemindUsersQuery;
import com.qijian.system.domain.vo.RemindUsersVo;
import com.qijian.system.domain.vo.RemindVo;
import com.qijian.system.mapper.RemindMapper;
import com.qijian.system.service.IRemindService;
import com.qijian.system.service.IRemindUsersService;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 【请填写功能名称】Service业务层处理
 *
 * @author qijian
 * @date 2022-08-24
 */
@Service
@RequiredArgsConstructor
public class RemindServiceImpl extends ServiceImpl<RemindMapper, Remind> implements IRemindService {

    private final RemindMapper remindMapper;
    private final IRemindUsersService remindUsersService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean addOrUpdateVo(RemindVo vo) {

        boolean isAdd = ObjectUtils.isNull(vo.getId());
        RemindUsers users = new RemindUsers();
        List<RemindUsers> usersAdd = new ArrayList<>();

        RemindQuery remindQuery = new RemindQuery();
        remindQuery.setType(vo.getType());
        remindQuery.setClassification(vo.getClassification());
        remindQuery.setConditions(StringUtils.isBlank(vo.getConditions()) ? " " : vo.getConditions());
        if (this.count(WhereEntityTool.invoke(remindQuery)) > 0) {
            throw new ServiceException("E01:相同类型、分类已存在");
        }
        if (isAdd) {
            vo.setId(IdUtils.singletonSnowId());
        } else {
            RemindUsersQuery remindUsersQuery = new RemindUsersQuery();
            remindUsersQuery.setMainId(vo.getId());
            remindUsersService.remove(WhereEntityTool.invoke(remindUsersQuery));
        }

        users.setMainId(vo.getId());
        users.setCustomType(vo.getCustomType());
        users.setCustomField(vo.getCustomField());

        this.saveOrUpdate(vo);

        if (vo.getCustomType() == 1) {
            remindUsersService.saveOrUpdate(users);
        } else {
            vo.getDetails().forEach(x -> {
                RemindUsers remindUsers = new RemindUsers();
                remindUsers.setId(null);
                remindUsers.setMainId(vo.getId());
                remindUsers.setCustomType(vo.getCustomType());
                remindUsers.setCustomField(null);
                remindUsers.setUserId(x.getUserId());
                remindUsers.setUserName(x.getUserName());
                usersAdd.add(remindUsers);
            });

            if (usersAdd.size() > 0) {
                remindUsersService.saveBatch(usersAdd);
            }
        }
        return true;
    }

    @Override
    public List<RemindVo> getVoById(Long id) {
        return remindMapper.getVoById(id);
    }

    @Override
    public List<SysUser> getUserByType(String simpleName) {
        return remindMapper.getUserByType(simpleName);
    }

    @Override
    public List<SysUser> getUser(Wrapper<RemindQuery> queryWrapper) {
        return remindMapper.getUser(queryWrapper);
    }

    @Override
    public List<RemindVo> getRemindVoList(@Param(Constants.WRAPPER) Wrapper<RemindQuery> queryWrapper) {
        return remindMapper.getRemindVoList(queryWrapper);
    }

    /**
     * 查询我的提醒中需要发邮件的人
     *
     * @param clazz 表的class
     * @param obj   表对象
     * @return
     */
    @Override
    public List<RemindUsersVo> getUserByType(Class clazz, Object obj) {
        RemindQuery remindQuery = new RemindQuery();
        remindQuery.setType(clazz.getSimpleName());
        List<RemindVo> remindList = this.getRemindVoList(WhereEntityTool.invoke(remindQuery));
        if (CollUtil.isEmpty(remindList)) {
            return CollUtil.newArrayList();
        }
        List<RemindUsersVo> emailList = new ArrayList<>();
        for (RemindVo remind : remindList) {

            // 没有conditions 直接把里面的人用与返回
            if (StringUtils.isEmpty(remind.getConditions())) {
                emailList.addAll(remind.getDetails());
                continue;
            }
            Map<String, Field> fieldMap = ReflectUtil.getFieldMap(clazz);
            JSONArray jsonArray = JSONUtil.parseArray(remind.getConditions());

            // 通过条件检验的标志
            boolean passFlag = true;
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject json = jsonArray.getJSONObject(i);
                String key = json.getStr("field");
                String value = json.getStr("value");
                Field field = fieldMap.get(key);
                if (field != null && !value.equals(ReflectUtil.getFieldValue(obj, key).toString())) {
                    passFlag = false;
                    break;
                }
            }
            if (passFlag) {
                emailList.addAll(remind.getDetails());
            }
        }
        return emailList;
    }

}
